package com.andnnl.event.dispatch;

import com.andnnl.event.events.Event;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 多线程事件处理机制
 * 思路是用队列暂存事件，然后若干个事件分发器将事件分发给指定数量的事件处理线程处理。
 * Created by chenss on 2021/5/11.
 */
public class EventManager {
    private static final int EVENT_QUEUE_LENGTH = 1000;
    private static final int DISPATCHER_NUM = 2;
    private static final int EVENT_HANDLER_NUM = 10;

    public BlockingQueue<Event> eventQueue = new LinkedBlockingQueue<Event>(EVENT_QUEUE_LENGTH);
    private ExecutorService eventHandlerPool;

    protected EventDispatcher createDispatcher() {
        EventDispatcher dispatcher = new EventDispatcher(this.eventQueue, this.eventHandlerPool);
        dispatcher.register(EventType.CREATE, CreateEventHandler.class);
        dispatcher.register(EventType.MODIFY, ModifyEventHandler.class);
        return dispatcher;
    }
//    protected EventDispatcher createDispatcher2() {
//        EventDispatcher dispatcher = new EventDispatcher(this.eventQueue, this.eventHandlerPool);
//        dispatcher.register(EventType.MODIFY, ModifyEventHandler.class);
//        return dispatcher;
//    }

    public void init() {
        eventHandlerPool = Executors.newFixedThreadPool(EVENT_HANDLER_NUM);
    }

    public void start() {
        createDispatcher().start();
//        createDispatcher2().start();
//        for (int i = 0; i < DISPATCHER_NUM; i++) {
//            createDispatcher().start();
//        }
    }

    public void notify(Event event) {
        try {
            eventQueue.put(event);
        } catch (InterruptedException e) {
        }
    }
}
